#! /usr/bin/perl
# Written by Marc Espie 2012, Public Domain
use strict;
use warnings;

@ARGV == 5 or
	die "Usage: $0 version src dest\n";

my ($vfname, $src, $dest, $pcin, $pcdest) = @ARGV;
open(my $fh, '<', $vfname)
	or die "Can't read $vfname: $!\n";
my $version = <$fh>;
chomp $version;
my @l = split(/\./, $version);
my $v2 = sprintf("%d%03d%03d", @l);

open(my $in, '<', $src)
	or die "Can't read $src: $!\n";
open(my $out, '>', $dest)
	or die "Can't write to $dest: $!\n";

select($out);

while (<$in>) {
	s/\-\-VERS\-\-/$version/;
	s/\-\-VERSION\-NUMBER\-\-/$v2/;
	s/\-\-SOURCE\-ID\-\-/OpenBSD/;

	if (m/^\#ifdef\s+SQLITE_INT64_TYPE/) {
		while(<$in>) {
			last if m/^\#endif/;
		}
		print "typedef int64_t sqlite_int64;\n";
		print "typedef uint64_t sqlite_uint64;\n";
	} else {
		print $_;
	}
	if (m/^\#\s*include\s*\<stdarg\.h\>/) {
		print "#include <stdint.h>\n";
	}
}

my $h = { prefix => '/usr',
	exec_prefix => '${prefix}',
	libdir => '${exec_prefix}/lib',
	includedir => '${prefix}/include',
	PACKAGE_VERSION => $version,
	LIBS => '' };

open(my $in2, '<', $pcin)
	or die "Can't read $pcin: $!\n";

open(my $out2, '>', $pcdest)
	or die "Can't write to $pcdest: $!\n";
select($out2);
while(<$in2>) {
	while (s/\@(.*?)\@/$h->{$1}/g) {}
	print;
}
